package com.example.administrator.printoutindemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.printoutindemo.services.Tools;
import com.example.administrator.printoutindemo.view.MyImageButton;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;
import com.jess.arms.utils.ArmsUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.zhinenghuacangku.mvp.ui.activity.ScanQRCodeActivity;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import com.jess.arms.base.BaseConstants;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;


public class StoreGCSJCutMidQRCActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private static final String WEBSERVICE_CONFIG = "webServiceInfo";
    private static final int STOP = 0;
    private static final int THREADING = 1;
    private static final int SUBMITSUCCESS = 2;
    private static final int SUBMITUNSUCESS = 3;
    private static final int NO_DATA = 5;
    ImageView mBtnRight;
    private MyImageButton store_btn_QRCode = null;
    private TextView s_qrc_projectname = null;
    private TextView s_qrc_material = null;
    private TextView s_qrc_fmmaterial = null;
    private TextView s_qrc_submitQuestion = null;
    private Button s_qrc_btn_submit = null;
    private OutStorageDetail outstoragedetail = null;
    private FmMaterialDetailInfo fmMaterialDetailInfo = null;
    private List<OutStorageDetail> li_outdetail = new ArrayList<>();
    private List<FmMaterialDetailInfo> li_fmdetail = new ArrayList<>();
    private String scanResult = "";
    private TextView s_qrc_readdress = null;
    private TextView s_qrc_reusername = null;
    private TextView s_qrc_rephone = null;
    private TextView s_gps_mjd;
    private TextView s_gps_mwd;
    @SuppressLint("HandlerLeak")
    Handler hanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOP:

                    if (li_outdetail.size() == 1) {
                        OutStorageDetail in = li_outdetail.get(0);

                        String projectname = Tools.ToDBC(Tools.stringFilter(in
                                .get_projectname()));
                        String material = Tools.ToDBC(Tools.stringFilter(in
                                .get_material()));
                        String fmmaterial = Tools.ToDBC(Tools.stringFilter(in
                                .get_fmmaterial()));
                        String readdress = Tools.ToDBC(Tools.stringFilter(in
                                .get_receive_address()));
                        String reusername = Tools.ToDBC(Tools.stringFilter(in
                                .get_receive_userName()));
                        String rephone = Tools.ToDBC(Tools.stringFilter(in
                                .get_receive_userPhone()));

                        String jd = Tools.ToDBC(Tools.stringFilter(in.get_jd()));

                        String wd = Tools.ToDBC(Tools.stringFilter(in.get_wd()));

                        s_qrc_projectname.setText(projectname);
                        s_qrc_material.setText(material);
                        s_qrc_fmmaterial.setText(fmmaterial);
                        s_qrc_readdress.setText(readdress);
                        s_qrc_reusername.setText(reusername);
                        s_qrc_rephone.setText(rephone);
                        s_gps_mjd.setText(jd);
                        s_gps_mwd.setText(wd);

                    }

                    LoadingDialogUtil.dismissDialog();

                    break;

                case THREADING:

                    LoadingDialogUtil.dismissDialog();

                    break;

                case SUBMITSUCCESS:
                    s_qrc_btn_submit.setVisibility(View.GONE);
                    Toast.makeText(StoreGCSJCutMidQRCActivity.this, "提交数据成功！",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;

                case SUBMITUNSUCESS:
                    Toast.makeText(StoreGCSJCutMidQRCActivity.this, "提交数据失败！",
                            Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();
                    break;
                case NO_DATA:
                    ArmsUtils.makeText(StoreGCSJCutMidQRCActivity.this, "二维码错误,没有查询到相关数据");
                    LoadingDialogUtil.dismissDialog();

                    break;
            }

        }
    };
    private SharedPreferences sPreferencces;
    private String[] permissions = {android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_activity_gcsj_qrcode);

        sPreferencces = getSharedPreferences(WEBSERVICE_CONFIG, 0);
        ToolbarUtils.initToolbarTitleBack(this, "工程审计");

        mBtnRight = findViewById(R.id.btnRight);
        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_scan));
        mBtnRight.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getPermission()) {
                    li_outdetail.clear();
                    toScanQRCodeActivity();
                }
            }
        });

        store_btn_QRCode = (MyImageButton) findViewById(R.id.store_btn_QRCode);
        s_qrc_projectname = (TextView) findViewById(R.id.s_qrc_projectname);
        s_qrc_material = (TextView) findViewById(R.id.s_qrc_material);
        s_qrc_fmmaterial = (TextView) findViewById(R.id.s_qrc_fmmaterial);
        s_qrc_submitQuestion = (TextView) findViewById(R.id.s_qrc_submitQuestion);
        s_qrc_btn_submit = (Button) findViewById(R.id.s_qrc_btn_submit);

        s_qrc_readdress = (TextView) findViewById(R.id.s_qrc_readdress);
        s_qrc_reusername = (TextView) findViewById(R.id.s_qrc_reusername);
        s_qrc_rephone = (TextView) findViewById(R.id.s_qrc_rephone);

        s_gps_mjd = (TextView) findViewById(R.id.s_gps_mjd);
        s_gps_mwd = (TextView) findViewById(R.id.s_gps_mwd);

        outstoragedetail = new OutStorageDetail(this);
        fmMaterialDetailInfo = new FmMaterialDetailInfo(this);

        store_btn_QRCode.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 扫码
                s_qrc_btn_submit.setVisibility(View.VISIBLE);
                Intent openCameraIntent = new Intent(
                        StoreGCSJCutMidQRCActivity.this, CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });

        s_qrc_btn_submit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 提交

                if (!scanResult.equals("")) {

                    LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);


                    new Thread(new Runnable() {

                        @Override
                        public void run() {


                            if (li_outdetail.size() > 0) {

                                OutStorageDetail o = li_outdetail.get(0);

                                String re = UploadOutDetail(o.get_out_storage_detail_Id());

                                if (re.equals("1")) {
                                    Message m = new Message();
                                    m.what = StoreGCSJCutMidQRCActivity.SUBMITSUCCESS;
                                    hanlder.sendMessage(m);

                                } else {
                                    Message m = new Message();
                                    m.what = StoreGCSJCutMidQRCActivity.SUBMITUNSUCESS;
                                    hanlder.sendMessage(m);
                                }
                            } else {
                                Message m = new Message();
                                m.what = StoreGCSJCutMidQRCActivity.NO_DATA;
                                hanlder.sendMessage(m);
                            }

                        }
                    }).start();

                }

            }
        });
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的照相使用权限", 103, permissions);
            return false;
        }

    }

    private void toScanQRCodeActivity() {
        Intent newIntent = new Intent(this, ScanQRCodeActivity.class);
        SharedPreferences.Editor editor = sPreferencces.edit();
        editor.putInt(SCAN_REQUEST_CODE, 101);
        editor.commit();
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    // 上传经度纬度及反馈问题
    private String UploadOutDetail(String out_storage_detail_Id) {

        String result = "0";

        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "UpdateOstatus";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreCutMidServivce.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("ostatus", "1");
            request.addProperty("out_storage_detail_Id", out_storage_detail_Id);
            // request.addProperty("sYardCode", "WLY");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                result = returnStr;

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 101) {
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("scan_result");
            // lbl_QRCode.setText(scanResult);

            LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);


            new Thread() {
                @Override
                public void run() {
                    List<OutStorageDetail> outStorageDetailList = GetOutStorageDetailFromWebService(scanResult);
                    if (outStorageDetailList != null && outStorageDetailList.size() > 0) {
                        li_outdetail.addAll(outStorageDetailList);
                    }

                    List<FmMaterialDetailInfo> fmMaterialDetailInfoList = GetFmMaterialDetailInfoFromWebService(scanResult);
                    if (fmMaterialDetailInfoList != null && fmMaterialDetailInfoList.size() > 0) {
                        li_fmdetail.addAll(fmMaterialDetailInfoList);
                    }


                    if (li_outdetail.size() == 1) {

                        OutStorageDetail o = li_outdetail.get(0);

                        Message m = new Message();
                        m.what = StoreGCSJCutMidQRCActivity.STOP;
                        hanlder.sendMessage(m);
                    } else {
                        Message m = new Message();
                        m.what = StoreGCSJCutMidQRCActivity.NO_DATA;
                        hanlder.sendMessage(m);
                    }
                }
            }.start();

        }
    }

    // 获取基本信息
    private List<OutStorageDetail> GetOutStorageDetailFromWebService(
            String out_storage_detail_Id) {

        List<OutStorageDetail> list = null;
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetListOutStorageByQRCodeCutMid";

            String url = "http://" + sPreferencces.getString("ip", "") + ":"
                    + sPreferencces.getString("Port", "")
                    + "/StoreCutMidServivce.asmx";


            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("out_storage_detail_Id", out_storage_detail_Id);
            // request.addProperty("pass", edtPwd.getText().toString());
            // request.addProperty("sYardCode", "WLY");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                if ("" != returnStr) {
                    returnStr = returnStr.substring(returnStr.lastIndexOf("["),
                            returnStr.length());

                    returnStr = returnStr.replace("\\", "");

                    list = outstoragedetail.getListFromJSON(returnStr);

                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    // 获取子物料信息
    private List<FmMaterialDetailInfo> GetFmMaterialDetailInfoFromWebService(
            String out_storage_detail_Id) {

        List<FmMaterialDetailInfo> list = null;
        try {
            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetListOutStorageByQRCodeCutMid";

            String url = "http://" + sPreferencces.getString("ip", "") + ":"
                    + sPreferencces.getString("Port", "")
                    + "/StoreCutMidServivce.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("out_storage_detail_Id", out_storage_detail_Id);
            // request.addProperty("pass", edtPwd.getText().toString());
            // request.addProperty("sYardCode", "WLY");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

                String returnStr = response.toString();

                if ("" != returnStr) {
                    returnStr = returnStr.substring(returnStr.lastIndexOf("["),
                            returnStr.length());

                    returnStr = returnStr.replace("\\", "");

                    list = fmMaterialDetailInfo.getListFromJSON(returnStr);

                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

}